package com.food.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.food.mapper.CommentsMapper;
import com.food.mapper.FoodsMapper;
import com.food.mapper.TypesMapper;
import com.food.pojo.Comments;
import com.food.pojo.Foods;

import com.food.pojo.FoodsDto;
import com.food.pojo.Types;
import com.food.service.CommentsService;
import com.food.service.FoodsService;
import com.food.util.UserCFUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class FoodsServiceImpl extends ServiceImpl<FoodsMapper, Foods> implements FoodsService {

    @Autowired
    FoodsMapper foodsMapper;
    @Autowired
    CommentsService commentsService;
    @Autowired
    TypesMapper typesMapper;
    @Autowired
    CommentsMapper commentsMapper;

    @Value("${minio.endpoint}")
    private String endpoint;

    /**
     * 热门美食查找
     * @param limit
     * @param fixed
     * @return
     */
       @Override
      public List<Foods> getPopularList(Integer limit,String fixed){
           QueryWrapper<Foods> queryWrapper = new QueryWrapper<>();
           //按照美食热度排序
           queryWrapper.orderByDesc("food_weight");
           if(!fixed.equals("全部地区"))
           {
               //模糊查找地区
               queryWrapper.like("food_location", fixed);
           }
           //限制返回的数量
           queryWrapper.last("limit "+limit);

           List<Foods> list = foodsMapper.selectList(queryWrapper);

           return list;
      }

    /**
     * 美食详情页信息
     * @param foodsId
     * @return
     */
      @Override
    public FoodsDto getDetailsList(Integer foodsId){
          FoodsDto foodsDto = new FoodsDto();
          Foods foods = foodsMapper.selectById(foodsId);
          //拷贝到数据传输类
          BeanUtils.copyProperties(foods, foodsDto);

          //查询评论信息
          List<Comments> comments = commentsService.selectFoodsId(foodsId);

          foodsDto.setComments(comments);

          return foodsDto;
    }


    /**
     * 调用UserCF工具类
     * @param userid
     * @return
     */
    public List<Integer> getRecommendation(Integer userid){
        List<Comments> comments = commentsMapper.selectList(new LambdaQueryWrapper<Comments>().eq(Comments::getUserId, userid));
        //有评价记录才可进行推荐
//        if(comments.size()>1){
//            return null;
//        }
        List<Comments> commentsAll = commentsMapper.selectList(new LambdaQueryWrapper<>());
        UserCFUtil recommendation = new UserCFUtil();

        commentsAll.stream().forEach(comment->{
            recommendation.addUserFood(Integer.parseInt(comment.getUserId()), Integer.parseInt(comment.getFoodId()), comment.getCommentStar());
        });
        // 计算相似度矩阵
        recommendation.computeSimilarityMatrix();
        //获得推荐美食id
        List<Integer> foodRecommendations = recommendation.getFoodRecommendations(userid, 20);

        return foodRecommendations;
    }

    /**
     * 根据用户的行为特征基于UserCF算法推荐美食
     * @param userId
     * @return
     */
    @Override
    public List<Foods> selectRecommendation(Integer userId,String fixed){
        List<Foods> foods=new ArrayList<>();
        List<Integer> recommendation = getRecommendation(userId);
        recommendation.stream().forEach(id->{
            List<Foods> foods1 = foodsMapper.selectList(new LambdaQueryWrapper<Foods>().eq(Foods::getFoodId, id).like(Foods::getFoodLocation, fixed));
            foods.addAll(foods1);
        });
        return foods;
    }

    /**
     * 地区特色美食分页查找
     * "fixed":"定位"，
     * "type":"类型"，
     * "star"："星级"，
     * "sort"：“排序方式",
     * "page":"当前页",
     * "limit":"每页条数",
     * @return
     */

    @Override
    public Page<Foods> getRecommend(String fixed, String type, Double star, String sort, Integer page, Integer limit) {

        //分页查询
        Page<Foods> pageNum = new Page<>(page, limit);
        QueryWrapper<Foods> foodsQueryWrapper = new QueryWrapper<>();

        if(!type.equals("全部")){
            //查询类型的id
            QueryWrapper<Types> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("type_name", type);
            List<Types> types = typesMapper.selectList(queryWrapper);

            foodsQueryWrapper.eq("type_id", types.get(0).getId());
        }
        if(!fixed.equals("全部地区"))
        {
            //模糊查找地区
            foodsQueryWrapper.like("food_location", fixed);
        }
        //按星级
        if(!star.equals(0.0)){
            foodsQueryWrapper.ge("food_score", star);
//            foodsQueryWrapper.eq("food_score", star);
        }
        //排序
        if(sort.equals("热搜优先")){
            foodsQueryWrapper.orderByDesc("food_weight");
        }else {
            if(sort.equals("好评优先")){
                foodsQueryWrapper.orderByDesc("food_score");
            }
        }

        foodsQueryWrapper.orderByAsc("food_id");
        Page<Foods> foodsPage = foodsMapper.selectPage(pageNum, foodsQueryWrapper);

        return foodsPage;
    }

    /**
     * 搜索地区美食分页查询
     * @param fixed
     * @param type
     * @param star
     * @param sort
     * @param keyword
     * @param page
     * @param limit
     * @return
     */
    @Override
    public Page<Foods> getSearch(String fixed, String type, Double star, String sort, String keyword, Integer page, Integer limit) {
        //分页查询
        Page<Foods> pageNum = new Page<>(page, limit);

        QueryWrapper<Foods> foodsQueryWrapper = new QueryWrapper<>();

        if(!fixed.equals("全部地区"))
        {
            //模糊查找地区
            foodsQueryWrapper.like("food_location", fixed);
//            foodsQueryWrapper.or().like("food_location", fixed);
        }
        //按介绍和名字模糊查询
        foodsQueryWrapper.and(wrapper->wrapper
                        .like("food_name", keyword)
                        .or()
                        .like("food_introduce", keyword)
        );
//        foodsQueryWrapper.or().like("food_name", keyword)
//                .or()
//                .like("food_introduce", keyword)
//        ;

        if(!type.equals("全部")){
            //查询类型的id
            QueryWrapper<Types> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("type_name", type);
            List<Types> types = typesMapper.selectList(queryWrapper);

            foodsQueryWrapper.eq("type_id", types.get(0).getId());
        }

        //按星级
        if(!star.equals(0.0)){
            foodsQueryWrapper.ge("food_score", star);
//            foodsQueryWrapper.eq("food_score", star);
        }
        if(sort.equals("热搜优先")){
            foodsQueryWrapper.orderByDesc("food_weight");
        }else {
            if(sort.equals("好评优先")){
                foodsQueryWrapper.orderByDesc("food_score");
            }
        }
        //最后按id进行排序
        foodsQueryWrapper.orderByAsc("food_id");
        Page<Foods> foodsPage = foodsMapper.selectPage(pageNum, foodsQueryWrapper);

        //进行url的拼接
        List<Foods> records = foodsPage.getRecords();
        for(Foods foods:records){
            foods.setFoodImage1(endpoint+foods.getFoodImage1());
            foods.setFoodImage2(endpoint+foods.getFoodImage2());
            foods.setFoodImage3(endpoint+foods.getFoodImage3());
        }
        foodsPage.setRecords(records);

        return foodsPage;
    }

}
